import axios from 'axios';
import { Message } from 'element-ui';
import store from '@/store';
import router from '@/route';
import { getToken } from '@/utils/auth';
// create an axios instance
const service = axios.create({
  // withCredentials: true, // senVUE_APP_BASE_APId cookies when cross-domain requests
  timeout: 5000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      config.headers['Authorization'] = getToken();
    }
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(

  response => {
    const res = response.data;
    // 直接写五个00000会报错
    if (Number(res.code) === Number('00000')) {
      return res;
    } else {
      console.log(res.msg);
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      });
      return Promise.reject(new Error(res.msg || 'Error'));
    }
  },
  error => {
    console.log(error.response); // for debug
    const { data } = error.response;
    if (/10$/.test(data.code) || /11$/.test(data.code)) {
      Message({
        message: data.msg,
        type: 'error',
        duration: 5 * 1000
      });
      store.dispatch('user/resetToken').then(() => {
        router.push({ path: '/login' });
      });
    } else {
      Message({
        message: data.msg,
        type: 'error',
        duration: 5 * 1000
      });
    }
    return Promise.reject(error);
  }
);

export default service;
